package com.qk.aspect;

import com.qk.entity.OperateLog;
import com.qk.mapper.OperateMapper;
import com.qk.utils.CurrentUserHoler;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect//切面
@Component
public class OperateLogAspect {
    @Autowired
    private OperateMapper operateMapper;

    /**
     * 记录日志
     */
    @Around("@annotation(com.qk.anno.Log)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateUserId(CurrentUserHoler.getCurrentUser());//获取用户ID
        operateLog.setOperateTime(LocalDateTime.now());//获取操作时间
        operateLog.setClassName(pjp.getTarget().getClass().getName());//获取类名
        operateLog.setMethodName(pjp.getSignature().getName());//获取方法名
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));//获取参数

        //获取数据的返回值
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        operateLog.setReturnValue(result.toString());//获取返回值
        operateLog.setCostTime(end - start);//获取耗时


        //调用数据库增加日志
        operateMapper.insert(operateLog);
        return result;
    }
}
